#include "Components.h"
#include <Renderer/SDLRenderer/SDLTexture.h>

namespace Engine2D
{
    RenderTextureComponent::RenderTextureComponent()
    {
        fileName.resize(256);
        srcSize = SLua_Vec2{100, 100};
        dstSize = SLua_Vec2{100, 100};
    }

    void RenderTextureComponent::Load()
    {
        auto sdltexture = std::make_shared<SDLTexture>();
        if (sdltexture->Load(fileName)) {
            texture = sdltexture;
        }
    }

    void RenderTextureComponent::OnTick(IObject *obj)
    {
        auto trans = this->GetComponentMessage<TransformMessage>();
        glm::vec4 srcPos = trans.GetTransform() * SLua_Vec4{-srcSize.x / 2, -srcSize.y / 2, 0.0f, 1.0f}.ToGlm();
        glm::vec4 dstPos = trans.GetTransform() * SLua_Vec4{-dstSize.x / 2, -dstSize.y / 2, 0.0f, 1.0f}.ToGlm();
        SLua_Rect srcRect{(int)srcPos.x, (int)srcPos.y, srcSize.x, srcSize.y};
        SLua_Rect dstRect{(int)dstPos.x, (int)dstPos.y, dstSize.x, dstSize.y};
        if (texture) {
            Renderer::Instance()->DrawTexture(texture, std::optional<SLua_Rect>(srcRect), std::optional<SLua_Rect>(dstRect));
        }
    }

} // namespace Engine2D
